package com.wanban.downloader.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.wanban.downloader.model.M3U8;
import com.wanban.downloader.model.M3U8Seg;
import com.wanban.downloader.model.Status;
import com.wanban.downloader.utils.CommonUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class M3u8VideoDownloadDatabaseHelper {
    private M3U8DownloadSQLiteHelper mSQLiteHelper;

    public M3u8VideoDownloadDatabaseHelper(Context context) {
        if (context == null) {
            return;
        }
        mSQLiteHelper = new M3U8DownloadSQLiteHelper(context);
    }

    public void markDownloadInfoAddEvent(DownloadEntity item) {
        SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
        if (db == null) {
            return;
        }
        synchronized (this) {
            if (isTaskInfoExistInTable(db, item)) {
            } else {
                insertVideoDownloadInfo(db, item);
            }
        }
    }

    public long markDownloadUpdateEvent(DownloadEntity item) {
        SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
        if (db == null) {
            return -1L;
        }
        if (isTaskInfoExistInTable(db, item)) {
            return updateDownloadProgressInfo(db, item);
        } else {
            return insertVideoDownloadInfo(db, item);
        }
    }


    public long updateDownloadProgressInfo(SQLiteDatabase db, DownloadEntity item) {
        long index = -1;
        if (db == null) {
            return index;
        }
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            values.put(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID, item.getVideoId());
            values.put(M3U8DownloadSQLiteHelper.Columns.STATE, item.getState());
            values.put(M3U8DownloadSQLiteHelper.Columns.EPISODE, item.getEpisode());
            values.put(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID, item.getSourceId());
            values.put(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME, item.getRetryTime());
            values.put(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME, item.getWatchTime());
            values.put(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH, item.getContentLength());
            values.put(M3U8DownloadSQLiteHelper.Columns.URL, item.getUrl());
            values.put(M3U8DownloadSQLiteHelper.Columns.COVER_URL, item.getCoverUrl());
            values.put(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME, item.getVideoName());
            values.put(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME, item.getEpisodeName());
            values.put(M3U8DownloadSQLiteHelper.Columns.FILE_PATH, item.getFilePath());
            values.put(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH, item.getCoverFilePath());
            M3U8 m3U8 = item.getM3u8();
            if (m3U8 != null) {
                String m3u8Json = new Gson().toJson(m3U8);
                values.put(M3U8DownloadSQLiteHelper.Columns.M3U8, m3u8Json);
            }
            Map<String, String> header = item.getHeader();
            if (header != null) {
                values.put(M3U8DownloadSQLiteHelper.Columns.HEADER, CommonUtils.INSTANCE.map2String(header));
            }
            String whereClause = M3U8DownloadSQLiteHelper.Columns.URL + " = ?";
            String[] whereArgs = {item.getUrl()};
            index = db.update(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO, values, whereClause, whereArgs);
            db.setTransactionSuccessful();
            return index;
        } catch (Exception e) {
            Log.d("Database", "updateVideoDownloadInfo failed, exception = " + e.getMessage());
            return index;
        } finally {
            db.endTransaction();
        }
    }

    private long insertVideoDownloadInfo(SQLiteDatabase db, DownloadEntity item) {
        long index = -1;
        if (db == null) {
            return index;
        }
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            values.put(M3U8DownloadSQLiteHelper.Columns.URL, item.getUrl());
            values.put(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID, item.getVideoId());
            values.put(M3U8DownloadSQLiteHelper.Columns.STATE, item.getState());
            values.put(M3U8DownloadSQLiteHelper.Columns.EPISODE, item.getEpisode());
            values.put(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID, item.getSourceId());
            values.put(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME, item.getRetryTime());
            values.put(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME, item.getWatchTime());
            values.put(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH, item.getContentLength());
            values.put(M3U8DownloadSQLiteHelper.Columns.COVER_URL, item.getCoverUrl());
            values.put(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME, item.getVideoName());
            values.put(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME, item.getEpisodeName());
            values.put(M3U8DownloadSQLiteHelper.Columns.FILE_PATH, item.getFilePath());
            values.put(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH, item.getCoverFilePath());
            M3U8 m3U8 = item.getM3u8();
            if (m3U8 != null) {
                values.put(M3U8DownloadSQLiteHelper.Columns.M3U8, new Gson().toJson(m3U8));
            }
            Map<String, String> header = item.getHeader();
            if (header != null) {
                values.put(M3U8DownloadSQLiteHelper.Columns.HEADER, CommonUtils.INSTANCE.map2String(header));
            }
            index = db.insert(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO, null, values);
            db.setTransactionSuccessful();
            return index;
        } catch (Exception e) {
            Log.w("DB", "insertVideoDownloadInfo failed, exception = " + e.getMessage());
            return index;
        } finally {
            db.endTransaction();

        }
    }

    private boolean isTaskInfoExistInTable(SQLiteDatabase db, DownloadEntity item) {
        if (db == null)
            return false;
        Cursor cursor = null;
        try {
            String selection = M3U8DownloadSQLiteHelper.Columns.URL + " = ?";
            String[] selectionArgs = {item.getUrl()};
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO, null,
                    selection, selectionArgs, null, null, null, null);
            if (cursor != null && cursor.moveToFirst() && !TextUtils.isEmpty(cursor.getString(0))) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.w("DB", "isTaskInfoExistInTable query failed, exception = " + e.getMessage());
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public DownloadEntity isAddedTask(String url) {
        SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
        if (db == null) {
            return null;
        }
        Cursor cursor = null;
        try {
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO,
                    null,
                    M3U8DownloadSQLiteHelper.Columns.URL + " = ?", new String[]{url},
                    null, null, null, null);
            if (cursor == null)
                return null;
            DownloadEntity item = null;
            if (cursor.moveToNext()) {
                String downloadUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.URL));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME));
                String coverUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_URL));
                item = new DownloadEntity(downloadUrl, videoName, coverUrl);
                item.setVideoId(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID)));
                item.setState(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.STATE)));
                item.setEpisode(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE)));
                item.setSourceId(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID)));
                item.setRetryTime(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME)));
                item.setWatchTime(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME)));
                item.setContentLength(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH)));
                item.setEpisodeName(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME)));
                item.setFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.FILE_PATH)));
                item.setCoverFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH)));
                String headerStr = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.HEADER));
                if (!TextUtils.isEmpty(headerStr)) {
                    item.setHeader(CommonUtils.INSTANCE.string2Map(headerStr));
                }
                String m3u8Json = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.M3U8));
                if (!TextUtils.isEmpty(m3u8Json)) {
                    item.setM3u8(new Gson().fromJson(m3u8Json, M3U8.class));
                }

            }
            return item;
        } catch (Exception e) {
            Log.w("DB", "getDownloadInfos failed, exception = " + e.getMessage());
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public DownloadEntity getDownloadTask(long video, int episode, int sourceId) {
        SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
        if (db == null) {
            return null;
        }
        Cursor cursor = null;
        try {
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO,
                    null,
                    M3U8DownloadSQLiteHelper.Columns.VIDEO_ID + " = ? AND " +
                            M3U8DownloadSQLiteHelper.Columns.EPISODE + " = ? AND " +
                            M3U8DownloadSQLiteHelper.Columns.SOURCE_ID + " = ?",
                    new String[]{String.valueOf(video), String.valueOf(episode), String.valueOf(sourceId)},
                    null, null, null, null);
            if (cursor == null)
                return null;
            DownloadEntity item = null;
            if (cursor.moveToNext()) {
                String downloadUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.URL));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME));
                String coverUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_URL));
                item = new DownloadEntity(downloadUrl, videoName, coverUrl);
                item.setVideoId(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID)));
                item.setState(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.STATE)));
                item.setEpisode(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE)));
                item.setSourceId(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID)));
                item.setRetryTime(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME)));
                item.setWatchTime(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME)));
                item.setContentLength(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH)));
                item.setEpisodeName(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME)));
                item.setFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.FILE_PATH)));
                item.setCoverFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH)));
                String headerStr = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.HEADER));
                if (!TextUtils.isEmpty(headerStr)) {
                    item.setHeader(CommonUtils.INSTANCE.string2Map(headerStr));
                }
                String m3u8Json = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.M3U8));
                if (!TextUtils.isEmpty(m3u8Json)) {
                    item.setM3u8(new Gson().fromJson(m3u8Json, M3U8.class));
                }

            }
            return item;
        } catch (Exception e) {
            Log.w("DB", "getDownloadInfos failed, exception = " + e.getMessage());
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    public ArrayList<DownloadEntity> getDownloadTaskByVideoId(long videoId) {
        SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
        if (db == null) {
            return null;
        }
        Cursor cursor = null;
        try {
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO,
                    null,
                    M3U8DownloadSQLiteHelper.Columns.VIDEO_ID + " = ? AND " + M3U8DownloadSQLiteHelper.Columns.STATE + " = ?",
                    new String[]{ String.valueOf(videoId), String.valueOf(Status.SUCCESS) },
                    null, null, null, null);
            if (cursor == null)
                return null;
            ArrayList<DownloadEntity> tasks = new ArrayList<>();

            while (cursor.moveToNext()) {
                String downloadUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.URL));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME));
                String coverUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_URL));
                DownloadEntity item = new DownloadEntity(downloadUrl, videoName, coverUrl);
                item.setVideoId(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID)));
                item.setState(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.STATE)));
                item.setEpisode(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE)));
                item.setSourceId(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID)));
                item.setRetryTime(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME)));
                item.setWatchTime(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME)));
                item.setContentLength(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH)));
                item.setEpisodeName(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME)));
                item.setFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.FILE_PATH)));
                item.setCoverFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH)));
                String headerStr = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.HEADER));
                if (!TextUtils.isEmpty(headerStr)) {
                    item.setHeader(CommonUtils.INSTANCE.string2Map(headerStr));
                }
                String m3u8Json = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.M3U8));
                if (!TextUtils.isEmpty(m3u8Json)) {
                    item.setM3u8(new Gson().fromJson(m3u8Json, M3U8.class));
                }
                tasks.add(item);
            }
            return tasks;
        } catch (Exception e) {
            Log.w("DB", "getDownloadInfos failed, exception = " + e.getMessage());
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    public Boolean hasDownloadingTask() {
        SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
        if (db == null) {
            return false;
        }
        Cursor cursor = null;
        try {
            boolean hasDownloading = false;
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO,
                    new String[]{M3U8DownloadSQLiteHelper.Columns.STATE}, null, null, null, null, null, null);
            if (cursor == null)
                return false;
            while (cursor.moveToNext()) {
                int status = cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.STATE));
                if (status != Status.SUCCESS && status != Status.DELETE) {
                    hasDownloading = true;
                    break;
                }
            }
            return hasDownloading;
        } catch (Exception e) {
            Log.w("DB", "getDownloadInfos failed, exception = " + e.getMessage());
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    public List<DownloadEntity> getDownloadInfos() {
        SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
        if (db == null) {
            return null;
        }
        List<DownloadEntity> items = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO,
                    null, null, null, null, null, null, null);
            if (cursor == null) return items;
            while (cursor.moveToNext()) {
                String url = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.URL));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME));
                String coverUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_URL));
                DownloadEntity item = new DownloadEntity(url, videoName, coverUrl);
                item.setVideoId(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID)));
                item.setState(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.STATE)));
                item.setEpisode(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE)));
                item.setSourceId(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID)));
                item.setRetryTime(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME)));
                item.setWatchTime(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME)));
                item.setContentLength(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH)));
                item.setEpisodeName(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME)));
                item.setFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.FILE_PATH)));
                item.setCoverFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH)));
                String m3u8Json = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.M3U8));
                if (!TextUtils.isEmpty(m3u8Json)) {
                    item.setM3u8(new Gson().fromJson(m3u8Json, M3U8.class));
                }
                String headerStr = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.HEADER));
                if (!TextUtils.isEmpty(headerStr)) {
                    item.setHeader(CommonUtils.INSTANCE.string2Map(headerStr));
                }
                items.add(item);
            }
        } catch (Exception e) {
            Log.w("DB", "getDownloadInfos failed, exception = " + e.getMessage());
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return items;

    }

    public ArrayList<DownloadEntity> getSuccessDownloads() {
        SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
        if (db == null) {
            return null;
        }
        ArrayList<DownloadEntity> items = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = db.query(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO,
                    null, M3U8DownloadSQLiteHelper.Columns.STATE +" = ?", new String[]{String.valueOf(Status.SUCCESS)}, null, null, null, null);
            if (cursor == null) return items;
            while (cursor.moveToNext()) {
                String url = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.URL));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_NAME));
                String coverUrl = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_URL));
                DownloadEntity item = new DownloadEntity(url, videoName, coverUrl);
                item.setVideoId(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.VIDEO_ID)));
                item.setState(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.STATE)));
                item.setEpisode(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE)));
                item.setSourceId(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.SOURCE_ID)));
                item.setRetryTime(cursor.getInt(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.RETRY_TIME)));
                item.setWatchTime(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.WATCH_TIME)));
                item.setContentLength(cursor.getLong(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.CONTENT_LENGTH)));
                item.setEpisodeName(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.EPISODE_NAME)));
                item.setFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.FILE_PATH)));
                item.setCoverFilePath(cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.COVER_FILE_PATH)));
                String m3u8Json = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.M3U8));
                if (!TextUtils.isEmpty(m3u8Json)) {
                    item.setM3u8(new Gson().fromJson(m3u8Json, M3U8.class));
                }
                String headerStr = cursor.getString(cursor.getColumnIndexOrThrow(M3U8DownloadSQLiteHelper.Columns.HEADER));
                if (!TextUtils.isEmpty(headerStr)) {
                    item.setHeader(CommonUtils.INSTANCE.string2Map(headerStr));
                }
                items.add(item);
            }
        } catch (Exception e) {
            Log.w("DB", "getDownloadInfos failed, exception = " + e.getMessage());
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return items;

    }

    public ArrayList<M3U8Seg> getTsList(JSONArray tsListJson){
        if (tsListJson == null) return null;
        int length = tsListJson.length();
        ArrayList<M3U8Seg> tsList = new ArrayList<>(length);
        for (int i = 0 ; i < length; i++) {
            M3U8Seg ts = new M3U8Seg();
            JSONObject obj = tsListJson.optJSONObject(i);
            if (obj == null) continue;
            ts.url = obj.optString("url");
            ts.name = obj.optString("name");
            ts.parentUrl = obj.optString("parentUrl");
            ts.method = obj.optString("method");
            ts.keyUri = obj.optString("keyUri");
            ts.keyIV = obj.optString("keyIV");
            ts.initSegmentUri = obj.optString("initSegmentUri");
            ts.segmentByteRange = obj.optString("segmentByteRange");

            ts.index = obj.optInt("index");
            ts.sequence = obj.optInt("sequence");
            ts.retryCount = obj.optInt("retryCount");


            ts.tsSize = obj.optLong("tsSize");
            ts.contentLength = obj.optLong("contentLength");

            ts.duration = (float) obj.optDouble("duration");

            ts.hasDiscontinuity = obj.optBoolean("hasDiscontinuity");
            ts.hasKey = obj.optBoolean("hasKey");
            ts.hasInitSegment = obj.optBoolean("hasInitSegment");

            tsList.add(ts);
        }
        return tsList;
    }

    public void deleteAllDownloadInfos() {
        SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
        if (db == null) {
            return;
        }
        db.beginTransaction();
        try {
            db.delete(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO, null, null);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.w("DB", "deleteAllDownloadInfos failed, exception = " + e.getMessage());
        } finally {
            db.endTransaction();
        }
    }

    public int deleteDownloadItemByUrl(String url) {
        int index = -1;
        SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
        if (db == null) {
            return index;
        }
        db.beginTransaction();
        try {
            String whereClause = M3U8DownloadSQLiteHelper.Columns.URL + " = ? ";
            String[] whereArgs = {url};
            index = db.delete(M3U8DownloadSQLiteHelper.TABLE_VIDEO_DOWNLOAD_INFO, whereClause, whereArgs);
            db.setTransactionSuccessful();
            return index;
        } catch (Exception e) {
            Log.w("DB", "deleteDownloadItemByUrl failed, exception = " + e.getMessage());
            return index;
        } finally {
            db.endTransaction();
        }
    }

}
